package com.infocollect.project.api.ui;

import com.infocollect.project.api.entity.TappMenuEntity;
import com.infocollect.project.api.entity.TappPowerMenuEntity;
import com.infocollect.project.api.entity.TappRoleEntity;
import com.infocollect.project.api.helper.CurrentHelp;
import com.infocollect.project.api.helper.MapHelper;
import com.infocollect.project.api.service.ITappMenuService;
import com.infocollect.project.api.service.ITappPowerMenuService;
import com.infocollect.project.api.service.ITappRoleService;
import com.infocollect.project.api.vo.CurrentUserInfoVO;
import com.infocollect.project.api.vo.OrganSearchVO;
import com.infocollect.project.api.vo.RoleUserVO;
import com.infocollect.project.form.vo.R;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * (TappRole)表控制层
 *
 * @author makejava
 * @since 2019-12-25 10:32:31
 */
@Api(value = "Role", tags = "角色信息")
@RestController
@RequestMapping("Role")
public class TappRoleController {
    /**
     * 服务对象
     */
    @Resource
    private ITappRoleService tappRoleService;
    /**
     * 服务对象
     */
    @Resource
    private ITappPowerMenuService tappPowermenuService;

    /**
     * 服务对象
     */
    @Resource
    private ITappMenuService tappMenuService;
    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation("获取角色信息")
    @PostMapping("selectOne/{id}")
    @ResponseBody
    public R<TappRoleEntity> selectOne(@PathVariable(name = "id") Long id) throws IOException {
        return R.newOk( this.tappRoleService.queryById(id));
    }
    /**
     * 通过主键查询单条数据
     *
     * @param  param post过来的参数
     * @return 单条数据
     */
    @ApiOperation("查询角色列表")
    @PostMapping("Query")
    public R<List<TappRoleEntity>> queryPageList(@RequestBody Map<String,String> param) throws Exception {

        TappRoleEntity entity=new TappRoleEntity();
        MapHelper.setObjectValue(entity,param);
        int page =Integer.parseInt(param.get("page")) ;
        int rows = Integer.parseInt(param.get("rows"));
        PageHelper.startPage(page, rows);
        List<TappRoleEntity> list= this.tappRoleService.queryAll(entity);
        PageInfo pageInfo = new PageInfo(list);
        return R.newOk(list,(int)pageInfo.getTotal());

    }
    /**
     * 保存角色信息
     * @param
     * @return
     * @throws IOException
     */
    @ApiOperation("保存角色信息")
    @PostMapping("SaveData")
    @ResponseBody
    public R<TappRoleEntity> SaveData(@RequestBody Map<String,String> param) throws IOException{

        if(param.get("frolename")==null||param.get("frolename").length()==0){
            return R.newError("角色名称不能为空！");
        }
        try {
            TappRoleEntity entity =param.get("fid")==null?null: this.tappRoleService.queryById(Long.parseLong(param.get("fid")) );
            CurrentUserInfoVO currentUserInfo= CurrentHelp.Ins.GetUser();
            if (entity == null) {
                entity=new TappRoleEntity();
                entity.setFcreateby(currentUserInfo.getUserName());
                entity.setFlastupdateby(currentUserInfo.getUserName());
                entity.setFcreationdate(new Date());
                entity.setFlastupdatedate(new Date());
                MapHelper.setObjectValue(entity,param);
                entity.setFstate("1");
                entity.setFroletype("0");///0普通角色 1公共角色 2管理员角色
                entity = this.tappRoleService.insert(entity);
            }else{
                entity.setFlastupdateby(currentUserInfo.getUserName());
                entity.setFlastupdatedate(new Date());
                MapHelper.setObjectValue(entity,param);
                entity= this.tappRoleService.update(entity);
            }
           return R.newOk(entity);
        }catch (Exception ex){
           return    R.newError("保存报错！具体错误信息为："+ex);
        }

    }

    /**
     * 保存机构信息
     * @param
     * @return
     * @throws IOException
     */
    @ApiOperation("角色停止或启动")
    @PostMapping("StopOrStart/{id}/{status}")
    @ResponseBody
    public  R<String> StopOrStart(@PathVariable(name = "id") Long id, @PathVariable(name = "status") String state)throws IOException {

        TappRoleEntity entity =new TappRoleEntity();
        entity.setFid(id);
        entity.setFstate(state);
        entity= this.tappRoleService.update(entity);
        if(entity==null){
            return R.newError("操作失败！");
        }else{
            return R.newOk("操作成功！");
        }

    }

    /**
     *
     * @return 加载角色授权菜单
     * @throws IOException
     */
    @ApiOperation("加载角色授权菜单")
    @PostMapping("LoadRolePower/{id}")
    @ResponseBody
    public  R<List<Map<String,Object>>>  LoadRolePower(@PathVariable(name = "roleid") Long roleid)throws IOException{

        List<TappMenuEntity> menulist=tappMenuService.queryAll(null);
        List<TappPowerMenuEntity> tappPowermenuList=tappPowermenuService.queryByRoleId(roleid);
        List<Long> powermenuList=new ArrayList<>();
        return R.newOk (getChildResourceByPId(menulist,tappPowermenuList,null,powermenuList));    }

    /**
     *
     * @return 返回菜单权限
     * @throws IOException
     */
    @ApiOperation("加载角色菜单")
    @PostMapping("LoadRoleMenuPower/{id}")
    @ResponseBody
    public  R< Map<String,Object>>  LoadRoleMenuPower(@PathVariable(name = "id") Long roleid)throws IOException{

        List<TappMenuEntity> menulist=tappMenuService.queryAll(null);
        List<TappPowerMenuEntity> tappPowermenuList=tappPowermenuService.queryByRoleId(roleid);
        Map<String,Object> resultdata=new HashMap<>();
        Long rootMenuId=  menulist.stream().filter(ee-> ee.getFparentid()==null).findFirst().get().getFid();
        List<Long> powermenuList= tappPowermenuList.stream().filter(ee->ee.getFmenuid()!=rootMenuId).map(Book -> Book.getFmenuid()).collect(Collectors.toList());
        resultdata.put("menulist",getChildResourceByPId(menulist,tappPowermenuList,null,powermenuList));
        resultdata.put("powermenu",powermenuList);
        // tappPowermenuList.stream().filter(ff->ff.getFmenuid().equals(1)).findFirst();
        return R.newOk (resultdata);
    }

    /**
     * 递归组装菜单树
     * @param menulist
     * @param pId
     * @return
     */
    List<Map<String,Object>> getChildResourceByPId(List<TappMenuEntity> menulist, List<TappPowerMenuEntity> tappPowermenuList, Long pId, List<Long> powermenuList){
        List<Map<String,Object>> child = new ArrayList<>();
        menulist.forEach(ee->{
            if(ee.getFparentid()!=null&&ee.getFparentid().equals(pId)){
                Map<String,Object> childitem=new HashMap<>();
                childitem.put("fid",ee.getFid());
                childitem.put("name",ee.getFmenuname());
                childitem.put("title",ee.getFmenuname());
                childitem.put("index",ee.getForderindex());
                childitem.put("code",ee.getFmenuurl());
                childitem.put("typeid",ee.getFtype());
                childitem.put("icon",ee.getFicon());
                childitem.put("icontype",ee.getFicontype());
                childitem.put("procbid",pId);
                childitem.put("key",ee.getFid());
                if(ee.getFtype()==1||ee.getFtype()==0){
                    powermenuList.remove(ee.getFid());
                }
                childitem.put("IsOpFrom",ee.getFisopfrom());
                childitem.put("children",getChildResourceByPId(menulist,tappPowermenuList,ee.getFid(),powermenuList));
                Optional<TappPowerMenuEntity> cartOptional = tappPowermenuList.stream().filter(ff->ff.getFmenuid().equals(ee.getFid())).findFirst();
                if (cartOptional.isPresent()) {
                    childitem.put("checked",true);
                    childitem.put("powerdata",cartOptional.get());
                } else {
                    childitem.put("checked",false);
                    childitem.put("powerdata","");
                }
                child.add(childitem);
            }
            else if(pId==null&&ee.getFparentid()==null){
                Map<String,Object> childitem=new HashMap<>();
                childitem.put("fid",ee.getFid());
                childitem.put("key",ee.getFid());
                childitem.put("name",ee.getFmenuname());
                childitem.put("title",ee.getFmenuname());
                childitem.put("index",ee.getForderindex());
                childitem.put("code",ee.getFmenuurl());
                childitem.put("typeid",ee.getFtype());
                if(ee.getFtype()==1||ee.getFtype()==0){
                    powermenuList.remove(ee.getFid());
                }
                childitem.put("icon",ee.getFicon());
                childitem.put("icontype",ee.getFicontype());
                childitem.put("procbid",pId);
                childitem.put("IsOpFrom",ee.getFisopfrom());
                childitem.put("children",getChildResourceByPId(menulist,tappPowermenuList,ee.getFid(),powermenuList));
                Optional<TappPowerMenuEntity> cartOptional = tappPowermenuList.stream().filter(ff->ff.getFmenuid().equals(ee.getFid())).findFirst();
                if (cartOptional.isPresent()) {
                    childitem.put("checked",true);
                    childitem.put("powerdata",cartOptional.get());
                } else {
                    childitem.put("checked",false);
                    childitem.put("powerdata","");
                }
                child.add(childitem);

            }

        });
        return child;
    }

    /**
     *
     * @return 返回角色成员
     * @throws IOException
     */
    @ApiOperation("角色成员")
    @PostMapping("getRoleUser")
    @ResponseBody
    public  R<List<RoleUserVO>> getRoleUser(@RequestBody Map<String,String> param)throws Exception{
        Long id=Long.parseLong(param.get("roleID"));
        RoleUserVO roleUser=new RoleUserVO();
        roleUser.setFroleid(id);
        roleUser.setName(param.get("MemberName"));
        roleUser.setTypename(param.get("TypeName"));
        int page =Integer.parseInt(param.get("page")) ;
        int rows = Integer.parseInt(param.get("rows"));
        PageHelper.startPage(page, rows);
        List<RoleUserVO> list= this.tappRoleService.getRoleMember(roleUser);
        PageInfo pageInfo = new PageInfo(list);
        return R.newOk(list,(int)pageInfo.getTotal());
    }

    /**
     * 角色选择控件
     * @param Search
     * @return
     * @throws Exception
     */
    @ApiOperation("角色搜索")
    @PostMapping("SearchRole")
    @ResponseBody
    public R<  List<OrganSearchVO>> SearchRole(@RequestParam("Search") String Search) throws Exception{
        TappRoleEntity roleentity=new TappRoleEntity();
        roleentity.setFrolename(Search);
        List<TappRoleEntity> list= this.tappRoleService.queryAll(roleentity);
        List<OrganSearchVO> searchList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            TappRoleEntity menuitem=list.get(i);
            OrganSearchVO entity = new OrganSearchVO();
            entity.setNo(menuitem.getFid().toString());
            entity.setName(menuitem.getFrolename());
            entity.setRealName(menuitem.getFrolename());
            entity.setGrandNo("");
            entity.setGrandName("");
            entity.setIsDept(0);
            entity.setDeptPName("");
            entity.setDeptPNo("");
            searchList.add(entity);
        }
        return R.newOk(searchList);
    }
    @ApiOperation("角色选择")
    @PostMapping("SelectRole")
    @ResponseBody
    public R<List<OrganSearchVO>> SelectRole(@RequestParam("Search") String Search) throws Exception{
        TappRoleEntity roleentity=new TappRoleEntity();
       /// roleentity.setFrolename(Search);
        List<TappRoleEntity> list= this.tappRoleService.queryAll(roleentity);
        List<OrganSearchVO> searchList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            TappRoleEntity menuitem=list.get(i);
            OrganSearchVO entity = new OrganSearchVO();
            entity.setNo(menuitem.getFid().toString());
            entity.setName(menuitem.getFrolename());
            entity.setRealName(menuitem.getFrolename());
            entity.setGrandNo("");
            entity.setGrandName("");
            entity.setIsDept(0);
            entity.setDeptPName("");
            entity.setDeptPNo("");
            searchList.add(entity);
        }
        return R.newOk(searchList);
    }
}